from django.shortcuts import render
from rest_framework.views import  APIView
from rest_framework.response import Response
from login import models, my_seralizers
from utils import random_code,my_redis #随机生成的验证码
from tools import send_code,jwt_token,imgage_captcha  #引入发送验证码的模块

import re
# Create your views here.


#验证码
class CodeView(APIView):
    def post(self,request):
        phone=request.data.get('phone')
        #判断手机号是否为空
        if not phone:
            return Response({'code': 100, 'msg': '手机号不能为空'})
        #判断手机号格式是否正确
        if not re.match(r'^1[3-9]\d{9}$', phone):
            return Response({'code': 100, 'msg': '手机号格式不正确'})

        if my_redis.My_Redis().get_code(phone):
            return Response({'code': 100, 'msg': '验证码已发送，请勿重复发送'})
        else:
            # 生成随机验证码
            code = random_code.generate_random_code()
            # 将验证码保存到redis中
            my_redis.My_Redis().set_code_time(phone=phone, time=60*60*2,code=code)
            # 发送验证码
            send_code.send_message(code, phone)
            return Response({'code': 200, 'msg': f'验证码:{code}发送成功'})

class LoginView(APIView):
    def post(self,request):
        # 获取请求中的用户名、密码和手机号
        password = request.data.get('password')
        phone=request.data.get('phone')
        my_code=request.data.get('code')

        # 判断用户名、密码和手机号是否为空
        if  not password or not phone:
            return Response({'message':'参数不完整'})

        # 使用正则表达式判断手机号格式是否正确
        re_phone=re.match(r'^1[3-9]\d{9}$',phone)
        if not re_phone:
            return Response({'message':'手机号格式不正确'})

        try:
            code=my_redis.My_Redis().get_code(phone)
            print(my_redis.My_Redis().get_code(phone))

            if code==my_code:
                #
                token = jwt_token.SimpleJWT().create_token(phone,60*3)
                user=models.User.objects.filter(phone=phone).first()
                mlist=[]
                all_data=models.Permission_Role.objects.all()
                print('+++++',user.roles.id)
                for i in all_data:
                    if i.role_id==user.roles:
                        mlist.append(i.permission_id.id)


                return Response({'message':'验证码正确，登陆成功','token':token,'user_id':user.id,'mlist':mlist})
            else:
                return Response({'message':'验证码错误'  })
        except Exception as e:
            print(f"Login error: {str(e)}")  # 打印错误日志方便调试
            return Response({'message': str(e)})  # 将异常转换为字符串




# 图片验证码视图
from rest_framework.renderers import BaseRenderer
from rest_framework import status


class PNGRenderer(BaseRenderer):
    media_type = 'image/png'
    format = 'png'
    charset = None
    render_style = 'binary'

    def render(self, data, media_type=None, renderer_context=None):
        return data


class ImageCaptchaAPIView(APIView):
    renderer_classes = [PNGRenderer]

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.captcha = imgage_captcha.ImageCaptcha()

    def get(self, request):
        """获取图片验证码"""
        phone=request.query_params.get('phone')
        captcha_text, image_stream = self.captcha.generate_captcha()
        # 存储验证码到Redis（5分钟=300秒过期）
        cache_key = f"image_captcha:{request.session.session_key}"
        my_redis.My_Redis().set_code_time(cache_key, 60,captcha_text )

        return Response(
            image_stream.getvalue(),
            content_type='image/png',
            status=status.HTTP_200_OK
        )

    def post(self, request):
        """验证图片验证码"""
        user_input = request.data.get('captcha', '').strip().lower()
        cache_key = f"image_captcha:{request.session.session_key}"
        captcha_text = my_redis.My_Redis().get_code(cache_key) or ''

        if not user_input:
            return Response(
                {'code': 100, 'msg': '请输入验证码'},
                status=status.HTTP_400_BAD_REQUEST
            )

        if not captcha_text:
            return Response(
                {'code': 100, 'msg': '验证码已过期，请重新获取'},
                status=status.HTTP_400_BAD_REQUEST
            )


        if user_input == captcha_text.lower():
            # 验证成功后删除验证码
            my_redis.My_Redis().r.delete(cache_key)
            return Response(
                {'code': 200, 'msg': '验证码正确'},
                status=status.HTTP_200_OK
            )

        return Response(
            {'code': 100, 'msg': '验证码错误'},
            status=status.HTTP_400_BAD_REQUEST
        )
